using UnityEngine;
using System.Collections;

/**
 * Script of fmusic management.
 * The purpose of this class is to keep music alive (yeah).
 * @author Benjamin Bruneau
 */
public class MusicScript : MonoBehaviour {
	
	private const string TAG_MENU_MUSIC = "menumusic"; // Menu Music Tag
	private const string TAG_GAME_MUSIC = "gamemusic"; // Game Music Tag
	private const string PAUSE_MANAGER_NAME = "PauseManager"; // PauseManager GameObject
	private const string RESULT_TEXT_NAME = "ResultText"; // PauseManager GameObject
	private const string SAVE_MANAGER_NAME = "SaveManager"; // Save Manager GameObject's name
	
	private const float VOLUME_MAX = 0.2f;
	private const float VOLUME_MIN = 0.04f;
	private const float VOLUME_ZERO = 0f;
	
	private GameObject _saveManager; // Save manager GameObject
	
	public bool _mute = false; // Mute music
		
	  /**
	 * Called on awake.
	 * @return void
	 */
	void Awake()
	{
		string tag = this.gameObject.tag;
		
		// If music playing, destroy new Musics
		GameObject[] musicTab = GameObject.FindGameObjectsWithTag(tag);
		
		if (musicTab.Length != 1)
		{
			Destroy(this.gameObject);
		}
	}
	    
	/**
	 * Called on initialization.
	 * @return void
	 */
	void Start ()
	{
	
		//Initialized because this object moves through scenes
		_saveManager = GameObject.Find (SAVE_MANAGER_NAME);
		
		string tag = this.gameObject.tag;
		string oppositeTag;
		
		// Shut down opposite music (game vs menu)
		if(tag.Equals(TAG_MENU_MUSIC))
		{
			oppositeTag = TAG_GAME_MUSIC;
			
		} else {
			
			oppositeTag = TAG_MENU_MUSIC;
			
		}
		
		GameObject[] musicTab = GameObject.FindGameObjectsWithTag(oppositeTag);
		
		foreach (GameObject item in musicTab) 
		{
			Destroy(item);
		}
		
		this.GetComponent<AudioSource>().Play();
		DontDestroyOnLoad(this);
		
	}
	
	/**
	 * Called once per frame.
	 * @return void
	 */
	void Update () {
	
		// If save Manager destroyed
		if(_saveManager == null)
		{
			_saveManager = GameObject.Find (SAVE_MANAGER_NAME);
		}
		
		_mute = _saveManager.GetComponent<SaveManagerScript>()._musicMute;
		
		if(!_mute)
		{
			GameObject pauseManager = GameObject.Find(PAUSE_MANAGER_NAME);
			GameObject resultText = GameObject.Find(RESULT_TEXT_NAME);
		
			if(pauseManager != null)
			{
				if(pauseManager.GetComponent<PauseControllerScript>()._pause)
				{
					this.GetComponent<AudioSource>().volume = VOLUME_MIN;
				} else {
					this.GetComponent<AudioSource>().volume = VOLUME_MAX;
				}
			} else {
				
				this.GetComponent<AudioSource>().volume = VOLUME_MAX;
				
			}
		
			if(resultText != null)
			{
				this.GetComponent<AudioSource>().volume = VOLUME_MIN;
			}
		} else {

			this.GetComponent<AudioSource>().volume = VOLUME_ZERO;
			
		}	
	}	
}
